/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { forwardRef, useCallback, useState, useImperativeHandle, useEffect } from 'react'
import { Form, Row, Col, Input, Select, Button } from 'antd'
import { debounce } from 'lodash'
import { connect } from 'dva'
const Option = Select.Option

const SearchBar = forwardRef(({ form, dispatch, loading }, ref) => {
  const [keywords, setKeywords] = useState("")
  const [phone, setPhone] = useState("")
  const [is_open, setOpen] = useState("all")
  const { getFieldDecorator, validateFields } = form

  useEffect(() => {
    search(1)
  }, [])

  const handleSubmit = useCallback(debounce((e) => {
    e.preventDefault()
    search(1)
  }, 500, {
    leading: true,
    trailing: false
  }), [])

  const search = (page=1) => {
    getFormValue(res=>{
      dispatch({
        type: "submissionRecords/getDispatchData",
        payload: {
          ...res,
          page
        }
      })
    })
  }

  const getFormValue = then => {
    validateFields((err, fieldsValue) => {
      const { keywords, phone, is_open } = fieldsValue
      if (err) return;
      setKeywords(keywords)
      setPhone(phone)
      setOpen(is_open)
      then(fieldsValue);
    });
  }

  useImperativeHandle(ref,()=>({
    search
  }),[])

  return (
    <Form onSubmit={handleSubmit} layout="inline" style={{marginBottom:"20px"}}>
      <Form.Item label="驿站名称：">
        {getFieldDecorator("keywords", {
          initialValue: keywords
        })(<Input type="text" placeholder="请输入驿站名称" allowClear />)}
      </Form.Item>
      <Form.Item label="手机号">
        {getFieldDecorator("phone", {
          initialValue: phone
        })(<Input type="text" placeholder="请输入手机号" allowClear />)}
      </Form.Item>
      <Form.Item label="开启上交快递费">
        {getFieldDecorator("is_open", {
          initialValue: is_open
        })(
          <Select
            showSearch
            placeholder="开启"
            style={{ width: "100px" }}
          >
            <Option key="all" value="all">全部</Option>
            <Option key={1} value={1}>开启</Option>
            <Option key={2} value={2}>未开启</Option>
          </Select>
        )}
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading}>
          查询
        </Button>
      </Form.Item>
    </Form>
  )
})

export default connect(({ loading })=>({
  loading: loading.effects["submissionRecords/getDispatchData"],
}), null, null, { forwardRef: true})(Form.create()(SearchBar))